package com.ly.mp.busicen.rule.field.execution;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ly.mp.busicen.rule.field.msg.IFieldMsgContainer;
import com.ly.mp.busicen.rule.field.validator.IValidData;
import com.ly.mp.busicen.rule.field.validator.IValidation;
import com.ly.mp.busicen.rule.field.validator.ValidData;
import com.ly.mp.busicen.rule.field.validator.ValidMsg;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;
import com.ly.mp.busicen.rule.field.validator.ValidatorContainer;

/**
 * 
 * @Description: 执行字段校验的, 报错之后使用t_prc_db_log_model中的内容 构建报错语言
 * @author wangzhen
 * @date 2024-01-24 04:31:28
 */
public class ValidExecution implements IValidExecution {

	Logger log = LoggerFactory.getLogger(ValidExecution.class);

	@Autowired
	ValidatorContainer validatorContainer;

	@Autowired
	IFieldMsgContainer fieldMsgContainer;

	public ValidResult validField(ValidFieldData field) {
		ValidResult result = new ValidResult();
		result.setFieldName(field.getFiledName());
		result.setField(field.getField());
		result.setValid(true);
		boolean flag = field.isAllCheck();
		// IValidation 中的statement 就是校验规则, 从VALIDATE_CONTENT 字段中拿到的
		for (IValidation validation : field.getValidations()) {
			String name = validation.name();
			ValidatorBase validatorBase = validatorContainer.get(name);
			if (validatorBase == null) {
				String errormsg = String.format("不存在类型【%s】的校验器", name);
				log.error(errormsg);
				throw new RuntimeException(errormsg);
			}			
			boolean isValid = validatorBase.valid(newValidData(field), validation);
			if (!isValid) {
				result.setValid(isValid);
				ValidMsg validMsg = validatorBase.errorMsg(validation);
				String msg = fieldMsgContainer.getMsg(validation.name(), validMsg.getMsg()).getMsg();
				String error = String.format(msg, strs2objs(validMsg.getParams()));
				result.addError(error);
				if (!flag) {
					break;
				}
			}
		}
		return result;
	}
	IValidData newValidData(ValidFieldData field) {
		ValidData validData = new ValidData();
		validData.setSource(field.getSource());
		validData.setValue(field.getValue());
		return validData;
	}
	private static Object[] strs2objs(String[] param) {
		if (param==null) {
			return null;
		}
		Object[] result = new Object[param.length];
		for (int i = 0; i < param.length; i++) {
			result[i]=param[i];
		}
		return result;
	}
	
}
